import 'package:audioplayers/audioplayers.dart';
import 'package:barcode_scan2/barcode_scan2.dart';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pomegranate/entity/book.dart';
import 'package:pomegranate/utils/local_storage.dart';
import 'package:vibration/vibration.dart';
import 'package:pomegranate/utils/api_service.dart';

import '../database.dart';

/// BarcodeProvider 是一个 ChangeNotifier 类，负责处理条形码扫描、声音和震动设置。
class BarcodeProvider extends ChangeNotifier {
  String barcodeScanRes = ''; // 条形码扫描结果
  bool isMuted = false; // 标志位，表示声音是否静音
  bool isVibrateOff = false; // 标志位，表示震动是否关闭

  int totalRecords = 0; // 总记录条数

  // 更新 barcodeScanRes 并通知监听器的方法
  void refreshCode(String code) {
    barcodeScanRes = code;
    notifyListeners();
  }

  AudioPlayer player = AudioPlayer(); // 用于播放声音的音频播放器

  // 异步方法，使用 BarcodeScanner 扫描条形码
  Future scanBarcodeNormal() async {
    refreshCode(''); // 重置 barcodeScanRes
    try {
      var result = await BarcodeScanner.scan(); // 调用扫描
      if (result.type.name == 'Barcode') {
        // 若成功返回对应 Barcode 标识，使用扫描结果更新 barcodeScanRes
        barcodeScanRes = result.rawContent;

        // 向后端请求 ISBN 数据
        final bookData = await ApiService().getInfoByIsbn(
            result.rawContent, '请填写appKey');
        Book book = Book(
            isbn: bookData['isbn'],
            bookName: bookData['bookName'],
            author: bookData['author'],
            press: bookData['press'],
            pressDate: bookData['pressDate'],
            pressPlace: bookData['pressPlace'],
            price: bookData['price'] * 1.0,
            pictures: bookData['pictures'],
            clcCode: bookData['clcCode'],
            clcName: bookData['clcName'],
            bookDesc: bookData['bookDesc'],
            binding: bookData['binding'],
            language: bookData['language'],
            format: bookData['format'],
            pages: bookData['pages'],
            edition: bookData['edition'],
            words: bookData['words']);
        final database = await $FloorAppDatabase.databaseBuilder('app_database.db').build();
        final bookDao = database.bookDao;
        bookDao.insertBook(book);

        totalRecords = await getTotalRecords(); // 更新总数据条数
      }
    } on PlatformException {
      barcodeScanRes = 'Failed to get platform version.'; // 处理平台版本异常
    }
    // if (!mounted) return;

    // 根据 barcodeScanRes 的值处理不同情况
    if (barcodeScanRes == "-1") {
      return refreshCode('');
    } else if (barcodeScanRes.isNotEmpty) {
      if (!isVibrateOff) {
        Vibration.vibrate(duration: 250);
      }
      if (!isMuted) {
        player.play(AssetSource('Barcode-scanner-beep-sound.mp3'), volume: .5);
      }
      return refreshCode(barcodeScanRes);
    } else {
      return refreshCode('');
    }
  }

  // 播放条形码扫描声音的方法
  void playSound() {
    player.play(AssetSource('Barcode-scanner-beep-sound.mp3'), volume: .2);
  }

  // 切换声音设置的异步方法
  Future toggleSound() async {
    isMuted = !isMuted; // 切换 isMuted 标志位
    await LocalStorage.setBool("Sound", isMuted); // 在本地存储中保存声音设置
    notifyListeners(); // 通知监听器设置已更改
  }

  // 切换震动设置的异步方法
  Future toggleVibration() async {
    isVibrateOff = !isVibrateOff; // 切换 isVibrateOff 标志位
    await LocalStorage.setBool("Vibration", isVibrateOff); // 在本地存储中保存震动设置
    notifyListeners(); // 通知监听器设置已更改
  }

  // 从本地存储中获取声音设置的异步方法
  Future getSound() async {
    isMuted =
        await LocalStorage.getBool("Sound") ?? false; // 获取声音设置，如果未找到，默认为 false
    notifyListeners(); // 通知监听器设置已更改
  }

  // 从本地存储中获取震动设置的异步方法
  Future getVibration() async {
    isVibrateOff = await LocalStorage.getBool("Vibration") ??
        false; // 获取震动设置，如果未找到，默认为 false
    notifyListeners(); // 通知监听器设置已更改
  }

  // 查询数据总条数
  Future<int> getTotalRecords() async {
    final database = await $FloorAppDatabase.databaseBuilder('app_database.db').build();
    final bookDao = database.bookDao;
    final result = await bookDao.getBookCount();
    return result ?? 0;
  }
}
